<?php
// $Id: mod_extcalendar_latest.php,v 0.7.2.6 2006/07/28 Exp $
//ExtCalendar Latest Events Module//
/**
* Content code
* @package Joomla Open Source
* @subpackage ExtCalendar
* @copyright (C) 2000 - 2006d
* @ All rights reserved
* @ Mambo Open Source is Free Software
* @ Released under GNU/GPL License : http://www.gnu.org/copyleft/gpl.html
**/

/**
* ExtCalendar Latest Events Module
*
* 2006/07/28 - Version 0.7.2.6
*
* Module for displaying upcoming events in connection with the ExtCalendar
* component, available at http://forge.joomla.org. The component must
* be installed before this module will work. There are some options for
* this module, which can be set in the "Parameters" section of the module
* in Administration.
*
*/

/* Deny direct access */
defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );

require_once ('mod_extcalendar_latest/extcal_latest_func.php');

if ( !defined('USER_IS_ADMIN') ) define('USER_IS_ADMIN',((($my->usertype == 'Administrator') || ($my->usertype == 'Super Administrator')) ? true : false));
if ( !defined('USER_IS_LOGGED_IN') ) define('USER_IS_LOGGED_IN',!($my->usertype == ''));

global $mosConfig_offset, $mosConfig_live_site, $mosConfig_lang, $mosConfig_locale, $CONFIG_EXT, $EXTCAL_CONFIG;

##-------------------We'll get the menu Itemid to pass on when clicking a link:

/* ### fix for artf3004 / artf3555 / post3774###  */
/* original comment by MF */
// I know there's a mainframe method for this (getItemid) but I can't figure the damn thing out. I think it's only for content items.
/* kwisatz: Jorge Muneo suggests to replace the old query with smth similar to this one. I've been searching for a decent joomla api documentation but couldn't find one, so we'll use this for now */

$qry = "SELECT MAX(id) FROM #__menu WHERE link LIKE '%com_extcalendar%' AND published <> '-2'";
$database->setQuery($qry);
$Itemid = $database->loadResult();

##-------------------Some little variables we'll use later:

$previouseventmonth = '';
$thiseventmonth = '';
$module_output = '';
$locale_was_set = false;
$rowsUpcoming = array();
$rowsUpcomingRecurrent = array();
$rowsRecent = array();
$rowsRecentRecurrent = array();

##-------------------EXTCAL_CONFIG will contain any important config variables we need:

$EXTCAL_CONFIG = array();
$EXTCAL_CONFIG['now'] = date( 'Y-m-d H:i:s', time() + $mosConfig_offset * 60 * 60 );
$EXTCAL_CONFIG['now_stamp'] = strtotime($EXTCAL_CONFIG['now']);
$EXTCAL_CONFIG['today_stamp'] = strtotime(substr($EXTCAL_CONFIG['now'],0,10));
$EXTCAL_CONFIG['Itemid'] = $Itemid;

  // There are two important values we need to get from the main ExtCal Settings, which the other module
  // and component load into something called $CONFIG_EXT. If these settings have already been loaded by
  // another module or component, we can save a query. Otherwise we query the settings table here.

if ( isset($CONFIG_EXT['show_recurrent_events']) && isset($CONFIG_EXT['addevent_allow_html']) && isset($CONFIG_EXT['who_can_add_events']) && isset($CONFIG_EXT['show_only_start_times']) ) {
  $EXTCAL_CONFIG['show_recurrent_events'] = $CONFIG_EXT['show_recurrent_events'];
  $EXTCAL_CONFIG['addevent_allow_html'] = $CONFIG_EXT['addevent_allow_html'];
  $EXTCAL_CONFIG['who_can_add_events'] = $CONFIG_EXT['who_can_add_events'];
  $EXTCAL_CONFIG['show_only_start_times'] = $CONFIG_EXT['show_only_start_times'];
  } else {
  $query = "SELECT name, value FROM #__extcal_config WHERE name = 'addevent_allow_html' OR name = 'show_recurrent_events' OR name = 'who_can_add_events' OR name = 'show_only_start_times'";
  $database->setQuery($query);
  $rows = $database->loadObjectList();
  foreach ($rows as $row) {
    $EXTCAL_CONFIG[$row->name] = $row->value;
  }
}

##-------------------Gather parameters from the module administration section:

$EXTCAL_CONFIG['display_if_no_events'] = intval($params->def('display_if_no_events',1));
$EXTCAL_CONFIG['number_of_events_to_list_upcoming'] = intval($params->def('number_of_events_to_list_upcoming',5));
$EXTCAL_CONFIG['number_of_events_to_list_recent'] = intval($params->def('number_of_events_to_list_recent',0));
$EXTCAL_CONFIG['title_max_length'] = intval($params->def('title_max_length',256));
$EXTCAL_CONFIG['show_times'] = intval($params->def('show_times',1));
$EXTCAL_CONFIG['show_category'] = intval($params->def('show_category',1));
$EXTCAL_CONFIG['show_description'] = intval($params->def('show_description',1));
$EXTCAL_CONFIG['description_max_length'] = intval($params->def('description_max_length',256));
$EXTCAL_CONFIG['preserve_linebreaks'] = intval($params->def('preserve_linebreaks',0));

//ADDED CONFIG for days ahead and display by category only!
$EXTCAL_CONFIG['number_of_days_to_list_ahead'] = intval($params->def('number_of_days_to_list_ahead',0));
$EXTCAL_CONFIG['categories_in_latest_cal'] = intval($params->def('categories_in_latest_cal',0));

// string handling not great, only works with comma delimiter.
if ($EXTCAL_CONFIG['categories_in_latest_cal'] == 1){
  //replace ', ' with ','
$EXTCAL_CONFIG['which_categories_to_list'] = str_replace(', ',',',$params->get('which_categories_to_list'));
    // add the rest to build the string...
$EXTCAL_CONFIG['which_categories_to_list'] = "AND cat_name IN ('".str_replace(',','\',\'',$EXTCAL_CONFIG['which_categories_to_list'])."')";
}else {
$EXTCAL_CONFIG['which_categories_to_list'] = "";
}
$EXTCAL_CONFIG['restrict_category_list'] = intval($params->def('restrict_category_list',0));
if ($EXTCAL_CONFIG['restrict_category_list'] == 1){
  //replace ', ' with ','
$EXTCAL_CONFIG['restricted_list_of_categories'] = str_replace(', ',',',$params->get('restricted_list_of_categories'));
    // add the rest to build the string...
$EXTCAL_CONFIG['restricted_list_of_categories'] = "AND cat_name IN ('".str_replace(',','\',\'',$EXTCAL_CONFIG['restricted_list_of_categories'])."')";
}else {
$EXTCAL_CONFIG['restricted_list_of_categories'] = "";
}
$strip_bbcode_from_description = intval($params->def('strip_bbcode_from_description',3));
/* ### fix for artf3455 ###  */ 
$EXTCAL_CONFIG['strip_bbcode_from_description'] = ( $strip_bbcode_from_description == 3 ) ? $EXTCAL_CONFIG['addevent_allow_html'] : $strip_bbcode_from_description;
$show_recurrent_events = intval($params->def('show_recurrent_events',3));
$EXTCAL_CONFIG['show_recurrent_events'] = ( $show_recurrent_events == 3 ) ? $EXTCAL_CONFIG['show_recurrent_events'] : $show_recurrent_events;
$EXTCAL_CONFIG['event_separator'] = trim($params->def('event_separator',''));
$EXTCAL_CONFIG['show_month_separators'] = intval($params->def('show_month_separators',0));
$rawMonthSeparatorStyle = htmlspecialchars(trim($params->def('month_separator_style','background-color: none; border-top-color: #777777; border-bottom-color: #777777; border-top-width: 1px; border-bottom-width: 1px; border-top-style: solid; border-bottom-style: solid; font-style: italic; font-weight: bold; margin: 4px; text-align: center')));
$EXTCAL_CONFIG['month_separator_style'] = ( $rawMonthSeparatorStyle == '' ) ? '' : ' style="'.str_replace(array("\r\n","\n"),'',$rawMonthSeparatorStyle).'"';
$EXTCAL_CONFIG['no_upcoming_events_text'] = $params->def('no_upcoming_events_text','There are no upcoming events currently scheduled.');
$EXTCAL_CONFIG['recent_events_text'] = $params->def('recent_events_text','Recent Events');
$rawRecentEventsStyle = htmlspecialchars(trim($params->def('recent_events_style','font-size: 110%; font-weight: bold; background-color: none; border-top-color: #333333; border-bottom-color: #333333; border-top-width: 2px; border-bottom-width: 2px; border-top-style: solid; border-bottom-style: solid; margin: 10px; text-align: center')));
$EXTCAL_CONFIG['recent_events_style'] = ( $rawRecentEventsStyle == '' ) ? '' : ' style="'.str_replace(array("\r\n","\n"),'',$rawRecentEventsStyle).'"';
$EXTCAL_CONFIG['show_full_calendar_link'] = intval($params->def('show_full_calendar_link',1));
$EXTCAL_CONFIG['full_calendar_link_text'] = htmlspecialchars($params->def('full_calendar_link_text','View Full Calendar'));
$EXTCAL_CONFIG['show_add_event_link'] = intval($params->def('show_add_event_link',0));
$EXTCAL_CONFIG['add_event_text'] = htmlspecialchars($params->def('add_event_text','Add New Event'));
$EXTCAL_CONFIG['use_extcal_locale_settings'] = intval($params->def('use_extcal_locale_settings',0));
$EXTCAL_CONFIG['time_format_12_or_24'] = intval($params->def('time_format_12_or_24',1));

##-------------------Query all upcoming events:

//MODIFIED: if new PARAM -> Restrict public view to certain categories
If (!$my->id AND $EXTCAL_CONFIG['restrict_category_list'] == 1)
    {
     $EXTCAL_CONFIG['which_categories_to_list'] = $EXTCAL_CONFIG['restricted_list_of_categories'];
    }

//MODIFIED: if new PARAM -> limit search to events earlier than day of NOW + $EXTCAL_CONFIG['number_of_days_to_list_ahead']
If ($EXTCAL_CONFIG['number_of_days_to_list_ahead'] == 0)
    {
    $calendarquery = "SELECT e.*,cat,cat_name from #__extcal_events AS e LEFT JOIN #__extcal_categories AS c ON e.cat=c.cat_id
	 WHERE ( ( ( UNIX_TIMESTAMP(e.end_date) >= UNIX_TIMESTAMP('".$EXTCAL_CONFIG['now']."') ) OR ( UNIX_TIMESTAMP(e.start_date) >= UNIX_TIMESTAMP('".$EXTCAL_CONFIG['now']."') ) )
	 OR  ( e.end_date = '0000-00-00 00:00:01'  AND  UNIX_TIMESTAMP(e.start_date) >= UNIX_TIMESTAMP('".$EXTCAL_CONFIG['now']."') ) )
	  AND c.published = '1' AND approved = '1' AND recur_type = '' ".$EXTCAL_CONFIG['which_categories_to_list']."
	   ORDER BY e.start_date,e.title ASC
	    LIMIT " . $EXTCAL_CONFIG['number_of_events_to_list_upcoming'];
        } else
        {
		/* ### fix for artf4535 ### */
    $calendarquery = "SELECT e.*,cat,cat_name from #__extcal_events AS e LEFT JOIN #__extcal_categories AS c ON e.cat=c.cat_id
	 WHERE ( ( ( UNIX_TIMESTAMP(e.end_date) BETWEEN UNIX_TIMESTAMP('".$EXTCAL_CONFIG['now']."') AND UNIX_TIMESTAMP(DATE_ADD('".$EXTCAL_CONFIG['now']."', INTERVAL '".$EXTCAL_CONFIG['number_of_days_to_list_ahead']."' DAY) ) ) OR (UNIX_TIMESTAMP(e.start_date) BETWEEN UNIX_TIMESTAMP('".$EXTCAL_CONFIG['now']."') AND UNIX_TIMESTAMP(DATE_ADD('".$EXTCAL_CONFIG['now']."', INTERVAL '".$EXTCAL_CONFIG['number_of_days_to_list_ahead']."' DAY)) ) )
         OR  ( e.end_date = '0000-00-00 00:00:01' AND UNIX_TIMESTAMP(e.start_date) BETWEEN UNIX_TIMESTAMP(DATE_SUB('".$EXTCAL_CONFIG['now']."', INTERVAL '".$EXTCAL_CONFIG['number_of_days_to_list_ahead']."' DAY)) AND UNIX_TIMESTAMP(DATE_ADD('".$EXTCAL_CONFIG['now']."', INTERVAL '".$EXTCAL_CONFIG['number_of_days_to_list_ahead']."' DAY))))
	  AND c.published = '1' AND approved = '1' AND recur_type = '' ".$EXTCAL_CONFIG['which_categories_to_list']."
	   ORDER BY e.start_date,e.title ASC
	    LIMIT " . $EXTCAL_CONFIG['number_of_events_to_list_upcoming'];
        }

$database->setQuery( $calendarquery );
$rowsUpcoming = $database->loadObjectList();

if ( $EXTCAL_CONFIG['show_recurrent_events'] == 2 ) { // Show only first occurrence of recurring events:

//MODIFIED: if new PARAM -> limit search to events earlier than day of Now + $EXTCAL_CONFIG['number_of_days_to_list_ahead']

If ($EXTCAL_CONFIG['number_of_days_to_list_ahead'] == 0)
    {
    $recurringquery = "SELECT e.*,cat,cat_name from #__extcal_events AS e LEFT JOIN #__extcal_categories AS c ON e.cat=c.cat_id
	 WHERE ( ( ( UNIX_TIMESTAMP(e.end_date) >= UNIX_TIMESTAMP('".$EXTCAL_CONFIG['now']."') ) OR ( UNIX_TIMESTAMP(e.start_date) >= UNIX_TIMESTAMP('".$EXTCAL_CONFIG['now']."') ) )
	 OR  ( e.end_date = '0000-00-00 00:00:01' AND  UNIX_TIMESTAMP(e.start_date) >= UNIX_TIMESTAMP('".$EXTCAL_CONFIG['now']."') ) )
	  AND c.published = '1' AND approved = '1' AND recur_type <> '' ".$EXTCAL_CONFIG['which_categories_to_list']."
	   ORDER BY e.start_date,e.title ASC
	    LIMIT " . $EXTCAL_CONFIG['number_of_events_to_list_upcoming'];
        } else
        {
    $recurringquery = "SELECT e.*,cat,cat_name from #__extcal_events AS e LEFT JOIN #__extcal_categories AS c ON e.cat=c.cat_id
    WHERE ( ( ( UNIX_TIMESTAMP(e.end_date) BETWEEN UNIX_TIMESTAMP('".$EXTCAL_CONFIG['now']."') AND UNIX_TIMESTAMP(DATE_ADD('".$EXTCAL_CONFIG['now']."', INTERVAL '".$EXTCAL_CONFIG['number_of_days_to_list_ahead']."' DAY) ) ) OR (UNIX_TIMESTAMP(e.start_date) BETWEEN UNIX_TIMESTAMP('".$EXTCAL_CONFIG['now']."') AND UNIX_TIMESTAMP(DATE_ADD('".$EXTCAL_CONFIG['now']."', INTERVAL '".$EXTCAL_CONFIG['number_of_days_to_list_ahead']."' DAY)) ) )
	 OR  ( e.end_date = '0000-00-00 00:00:01' AND  UNIX_TIMESTAMP(e.start_date) >= UNIX_TIMESTAMP('".$EXTCAL_CONFIG['now']."') ) )
	  AND c.published = '1' AND approved = '1' AND recur_type <> '' ".$EXTCAL_CONFIG['which_categories_to_list']."
	   ORDER BY e.start_date,e.title ASC
	    LIMIT " . $EXTCAL_CONFIG['number_of_events_to_list_upcoming'];
        }

  $database->setQuery( $recurringquery );
  $rowsUpcomingRecurrent = $database->loadObjectList();

  // Now we merge the arrays of non-recurrent and recurrent events:
  $rowsUpcoming = array_merge($rowsUpcoming,$rowsUpcomingRecurrent);

  // Now we sort the merged array by order of start date:
  usort( $rowsUpcoming, "sortUpcomingEvents" );

  // Now we've (possibly) added to the length of the array, we make sure it doesn't exceed our desired number of events:
  $rowsUpcoming = array_slice( $rowsUpcoming, 0, $EXTCAL_CONFIG['number_of_events_to_list_upcoming'] );

  }
 else if ($EXTCAL_CONFIG['show_recurrent_events']) { // Show each recurrence of an event separately:

  $rowsToAdd = array();
  $recurringquery = "SELECT e.*,cat,cat_name from #__extcal_events AS e LEFT JOIN #__extcal_categories AS c ON e.cat=c.cat_id
	 WHERE c.published = '1' AND approved = '1' AND recur_type <> '' ".$EXTCAL_CONFIG['which_categories_to_list']."
	   ORDER BY e.start_date,e.title ASC";

  $database->setQuery( $recurringquery );
  $rowsUpcomingRecurrent = $database->loadObjectList();
  // For each recurring event, parse all the recurrences and add those that fit our time window to the "$rowsToAdd" array:
  foreach ( $rowsUpcomingRecurrent as $row ) {
    if ( $row->recur_type != '' ) add_recurrent_dates( $row, $EXTCAL_CONFIG['number_of_events_to_list_upcoming'], $rowsToAdd, 'upcoming' );
  }
  // Now we merge the arrays of non-recurrent and recurrent events:
  $rowsUpcoming = array_merge($rowsUpcoming,$rowsToAdd);

  // Now we sort the merged array by order of start date:
  usort( $rowsUpcoming, "sortUpcomingEvents" );

  // Now we've (possibly) added to the length of the array, we make sure it doesn't exceed our desired number of events:

  $rowsUpcoming = array_slice( $rowsUpcoming, 0, $EXTCAL_CONFIG['number_of_events_to_list_upcoming'] );

}

##-------------------Query all recent events:

if ($EXTCAL_CONFIG['number_of_events_to_list_recent']) {

  $calendarquery = "SELECT e.*,cat,cat_name from #__extcal_events AS e LEFT JOIN #__extcal_categories AS c ON e.cat=c.cat_id
	 WHERE ( ( UNIX_TIMESTAMP(e.end_date) < UNIX_TIMESTAMP('".$EXTCAL_CONFIG['now']."') )
         OR  ( e.end_date = '0000-00-00 00:00:01' AND  UNIX_TIMESTAMP(e.start_date) >= UNIX_TIMESTAMP('".$EXTCAL_CONFIG['now']."') ) )
	  AND c.published = '1' AND approved = '1' AND recur_type = '' ".$EXTCAL_CONFIG['which_categories_to_list']."
	   ORDER BY e.start_date DESC,e.title ASC
	    LIMIT " . $EXTCAL_CONFIG['number_of_events_to_list_recent'];
  $database->setQuery( $calendarquery );
  $rowsRecent = $database->loadObjectList();

if ( $EXTCAL_CONFIG['show_recurrent_events'] == 3 ) { // Show only first occurrence of recurring events:

  $rowsToAdd = array();
  $recurringquery = "SELECT e.*,cat,cat_name from #__extcal_events AS e LEFT JOIN #__extcal_categories AS c ON e.cat=c.cat_id
	 WHERE ( UNIX_TIMESTAMP(e.end_date) < UNIX_TIMESTAMP('".$EXTCAL_CONFIG['now']."') ) AND ( UNIX_TIMESTAMP(e.start_date) < UNIX_TIMESTAMP('".$EXTCAL_CONFIG['now']."') )
	  AND c.published = '1' AND approved = '1' AND recur_type <> '' ".$EXTCAL_CONFIG['which_categories_to_list']."
	   ORDER BY e.start_date,e.title ASC";
  $database->setQuery( $recurringquery );
  $rowsRecentRecurrent = $database->loadObjectList();

  // Now we merge the arrays of non-recurrent and recurrent events:

  $rowsRecent = array_merge($rowsRecent,$rowsRecentRecurrent);

  // Now we sort the merged array by order of start date:

  function sortRecentEvents( $a, $b ) {
    if ( strtotime($a->start_date) == strtotime($b->start_date) ) return 0;
	return ( strtotime($a->start_date) > strtotime($b->start_date) ) ? -1 : 1;
  }

  usort( $rowsRecent, "sortRecentEvents" );

  // Now we've (possibly) added to the length of the array, we make sure it doesn't exceed our desired number of events:
  $rowsRecent = array_slice( $rowsRecent, 0, $EXTCAL_CONFIG['number_of_events_to_list_recent'] );

} else if ($EXTCAL_CONFIG['show_recurrent_events']) { // Show each recurrence of an event separately:

  $rowsToAdd = array();
  $recurringquery = "SELECT e.*,cat,cat_name from #__extcal_events AS e LEFT JOIN #__extcal_categories AS c ON e.cat=c.cat_id
	 WHERE ( UNIX_TIMESTAMP(e.end_date) < UNIX_TIMESTAMP('".$EXTCAL_CONFIG['now']."') )
	  AND c.published = '1' AND approved = '1' AND recur_type <> '' ".$EXTCAL_CONFIG['which_categories_to_list']."
	   ORDER BY e.start_date,e.title ASC";
  $database->setQuery( $recurringquery );
  $rowsRecentRecurrent = $database->loadObjectList();

  // For each recurring event, parse all the recurrences and add those that fit our time window to the "$rowsToAdd" array:

  foreach ( $rowsRecentRecurrent as $row ) {
    if ( $row->recur_type != '' ) add_recurrent_dates( $row, 1000, $rowsToAdd, 'recent' );
  }
  // Now we merge the arrays of non-recurrent and recurrent events:

  $rowsRecent = array_merge($rowsRecent,$rowsToAdd);

  // Now we sort the merged array by order of start date:

  function sortRecentEvents( $a, $b ) {
    if ( strtotime($a->start_date) == strtotime($b->start_date) ) return 0;
	return ( strtotime($a->start_date) > strtotime($b->start_date) ) ? -1 : 1;
  }
  usort( $rowsRecent, "sortRecentEvents" );

  // Now we've (possibly) added to the length of the array, we make sure it doesn't exceed our desired number of events:

  $rowsRecent = array_slice( $rowsRecent, 0, $EXTCAL_CONFIG['number_of_events_to_list_recent'] );

}

}

if ( ((count($rowsUpcoming) + count($rowsRecent)) > 0) || $EXTCAL_CONFIG['display_if_no_events'] ) {  // IF: Don't display if there are no events and the parameter is set not to

##-------------------First, set the proper locale if parameter says to:

if ( $EXTCAL_CONFIG['use_extcal_locale_settings'] ) {

	// Mambo already has a locale set in Site Configuration. If the locale code from the ExtCal language files

	// is NOT used, it just sticks with the one already set.

	$extcal_language_path = $mosConfig_absolute_path . "/components/com_extcalendar/languages/";
	if (!file_exists($extcal_language_path."{$mosConfig_lang}/index.php")) $mosConfig_lang = 'english';
	include $extcal_language_path."{$mosConfig_lang}/index.php";
	if ( isset($lang_info['locale']) && is_array($lang_info['locale']) ) {
		foreach( $lang_info['locale'] as $temp_lang_code ) {
			$locale_was_set =  setlocale (LC_TIME,$temp_lang_code);
		}
	}
}

##-------------------Second, define an important constant if not defined already:

if ( !defined('EXTCAL_TEXT_ALL_DAY') ) {
	if ( isset($lang_add_event_view) ) {
		define('EXTCAL_TEXT_ALL_DAY',$lang_add_event_view['all_day_label']);
	} else {
		$extcal_language_path = $mosConfig_absolute_path . "/components/com_extcalendar/languages/";
		if (!file_exists($extcal_language_path."{$mosConfig_lang}/index.php")) $mosConfig_lang = 'english';
		require_once $extcal_language_path."{$mosConfig_lang}/index.php";
		define('EXTCAL_TEXT_ALL_DAY',$lang_add_event_view['all_day_label']);
	}
}


$module_output .= "<h2>Coming Events</h2>\n"; # replace this with a variable

##-------------------Upcoming Events Section:

if ( count($rowsUpcoming) ) {
	$module_output_array = array();
	$extcounter = 0;

    $module_output .= "<ul>\n"; 

	foreach ( $rowsUpcoming as $thisEvent ) { // For each upcoming event we do:
	  $module_output_array[$extcounter] = '';
	  if ( $EXTCAL_CONFIG['show_month_separators'] ) { // If "Show Month Separators" is enabled in Administration, draw the month name:
		$thiseventmonth = strftime("%B",strtotime($thisEvent->start_date));
		if (($previouseventmonth == '') || ($thiseventmonth != $previouseventmonth)) {
		 // If this is a new month and it's not the first incident, we decrement the counter so that

		 // this event is simply added to the the previous array index. Now when we implode a few lines

		 // down, it won't add the event separator between the event and the month separator.
		 if ($extcounter) { array_pop($module_output_array); $extcounter--; }
		 $module_output_array[$extcounter] .= '<div'.$EXTCAL_CONFIG['month_separator_style'].'>' . ucwords($thiseventmonth) . '</div>';
		 $previouseventmonth = $thiseventmonth;
		}
	  }

	  $ext_event_link_URL = sefRelToAbs( 'index.php?option=com_extcalendar&amp;Itemid=' . $EXTCAL_CONFIG['Itemid'] . '&amp;extmode=view&amp;extid='. $thisEvent->extid );
	  $ext_full_calendar_URL = sefRelToAbs( 'index.php?option=com_extcalendar&amp;Itemid=' . $EXTCAL_CONFIG['Itemid'] );
	  // Actual output:

    
      $li_class = $extcounter % 2 == 0 ? "class='odd'" : "";
	  $module_output_array[$extcounter] .= '<li ' . $li_class . '>';

      $day_header = strftime("%B %e - %A",strtotime($thisEvent->start_date));
	  $module_output_array[$extcounter] .= '<b>' . $day_header . '</b>';

	  $module_output_array[$extcounter] .= "<table><tr>\n";
	  $module_output_array[$extcounter] .= "<td class='left_side'>" . strftime("%I:%M %p",strtotime($thisEvent->start_date)) . "</td>\n";
	  $module_output_array[$extcounter] .= "<td class='right_side'>";

	  $module_output_array[$extcounter] .= '<a href="' . $ext_event_link_URL . '">' . mf_shorten_with_ellipsis($thisEvent->title,$EXTCAL_CONFIG['title_max_length']) . '</a>';
	  $module_output_array[$extcounter] .= "</td>\n";

	  #$module_output_array[$extcounter] .= $EXTCAL_CONFIG['show_category'] ? '(<em>' . $thisEvent->cat_name . '</em>) ' : '';
	  #$module_output_array[$extcounter] .= $EXTCAL_CONFIG['show_description'] ? mf_shorten_with_ellipsis(process_extcal_description($thisEvent->description),$EXTCAL_CONFIG['description_max_length']) : '';
	  #$module_output_array[$extcounter] .= ($EXTCAL_CONFIG['show_category'] || $EXTCAL_CONFIG['show_description']) ? '<br />' : '';

	  $module_output_array[$extcounter] .= "</table></tr>\n";
	  $module_output_array[$extcounter] .= "</li>\n"; 
	  $extcounter++;
	}


	// We did this in an array so we can implode it and separate the entries with whatever we want.
	$module_output .= implode($EXTCAL_CONFIG['event_separator'],$module_output_array);

    $module_output .= "</ul>"; 
} else {
	$module_output .= $EXTCAL_CONFIG['no_upcoming_events_text'];
}

##-------------------Recent Events Section (if enabled in the module parameters):

if ( $EXTCAL_CONFIG['number_of_events_to_list_recent'] && (@count($rowsRecent) > 0) ) {
	$module_output .= '<div'.$EXTCAL_CONFIG['recent_events_style'].'>' . $EXTCAL_CONFIG['recent_events_text'] . '</div>';
	$module_output_array = array();
	$extcounter = 0;
	foreach ( $rowsRecent as $thisEvent ) { // For each upcoming event we do:
	  $module_output_array[$extcounter] = '';
	  if ( $EXTCAL_CONFIG['show_month_separators'] ) { // If "Show Month Separators" is enabled in Administration, draw the month name:
		$thiseventmonth = strftime("%B",strtotime($thisEvent->start_date));
		if (($previouseventmonth == '') || ($thiseventmonth != $previouseventmonth)) {
		 $module_output_recent[$extcounter] .= '<div'.$EXTCAL_CONFIG['month_separator_style'].'>' . ucwords($thiseventmonth) . '</div>';
		}
	  }

	  $ext_event_link_URL = sefRelToAbs( 'index.php?option=com_extcalendar&amp;Itemid=' . $EXTCAL_CONFIG['Itemid'] . '&amp;extmode=view&amp;extid='. $thisEvent->extid );
	  // Actual output:
	  $module_output_array[$extcounter] .= '<a href="' . $ext_event_link_URL . '">' . mf_shorten_with_ellipsis($thisEvent->title,$EXTCAL_CONFIG['title_max_length']) . '</a>';
	  $module_output_array[$extcounter] .= '<br />';
	  $module_output_array[$extcounter] .=  mf_get_daterange_string($thisEvent);
	  $module_output_array[$extcounter] .= '<br />';
	  $module_output_array[$extcounter] .= $EXTCAL_CONFIG['show_category'] ? '(<em>' . $thisEvent->cat_name . '</em>) ' : '';
	  $module_output_array[$extcounter] .= $EXTCAL_CONFIG['show_description'] ? mf_shorten_with_ellipsis(process_extcal_description($thisEvent->description),$EXTCAL_CONFIG['description_max_length']) : '';
	  $module_output_array[$extcounter] .= ($EXTCAL_CONFIG['show_category'] || $EXTCAL_CONFIG['show_description']) ? '<br />' : '';
	  $extcounter++;
	}

	// We did this in an array so we can implode it and separate the entries with whatever we want.

	$module_output .= implode($EXTCAL_CONFIG['event_separator'],$module_output_array);
}

##-------------------Extra Links to Full Calendar and Add New Event:

$module_output .= '<div class="footer">';

if ( $EXTCAL_CONFIG['show_full_calendar_link'] ) {
  $ext_full_calendar_URL = sefRelToAbs( 'index.php?option=com_extcalendar&amp;Itemid=' . $EXTCAL_CONFIG['Itemid'] );
  $module_output .= '<i><a href="'.$ext_full_calendar_URL.'">' . $EXTCAL_CONFIG['full_calendar_link_text'] . '</a></i>';
}

if ( $EXTCAL_CONFIG['show_add_event_link'] && latest_has_priv($EXTCAL_CONFIG['who_can_add_events']) ) {
  $ext_add_event_URL = sefRelToAbs( 'index.php?option=com_extcalendar&amp;Itemid=' . $EXTCAL_CONFIG['Itemid'] . '&amp;extmode=addevent' );
  $module_output .= '<a href="'.$ext_add_event_URL.'">' . $EXTCAL_CONFIG['add_event_text'] . '</a>';
}

$module_output .= '</div>';

##-------------------Set the locale for date/time functions back to the one already set by Mambo:

if ( $locale_was_set ) setlocale(LC_TIME,$mosConfig_locale);
echo $module_output;

} // ENDIF: Don't display if there are no events and the parameter is set not to
?>
